import axios from 'axios'
import { Message } from 'element-ui'
import config from '../config'

// 保存最近一次请求的信息 401时重新发起
const oldRequest = {}

// 超时时间
axios.defaults.timeout = 600000
// http请求拦截器
var loadinginstace
axios.interceptors.request.use(function (request) {
  // element ui Loading方法
  // loadinginstace = Loading.service({ fullscreen: true })
  if (!request.url.startsWith('http')) {
    request.url = config.apiServer + request.url
  }
  if (!request.headers.Authorization) {
    request.headers.Authorization = config.token.get()
  }

  oldRequest[request.url] = {
    tmpUrl: request.url,
    tmpData: request.data,
    method: request.method
  }

  return request
}, error => {
  loadinginstace.close()
  Message.error({
    message: '加载超时'
  })
  return Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(function (data) {
  // 响应成功关闭loading
  // loadinginstace.close()
  if (data.data.ok !== true) {
    Message.error({
      message: '错误:' + data.data.err.msg
    })
    return Promise.reject(data.data.err.msg)
    // throw Error(data.data.err.msg)
  } else if (data.config.method !== 'get') {
    if (data.config.msg === undefined) {
      Message.success({
        message: '操作成功！'
      })
    } else {
      if (data.config.msg.length !== 0) {
        Message.success({
          message: data.config.msg
        })
      }
    }
  }
  const result = data.data.data
  result.changes = data.data.changes
  return result || []
}, error => {
  if (error.response && error.response.status === 401) {
    Message.error({
      message: '登录超时，请重新登录'
    })
  } else {
    Message.error({
      message: '服务器错误！'
    })
    return Promise.reject(error)
  }
})
export default axios
